package com.lyk.coursearrange.common.exception.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.api.IErrorCode;
import com.lyk.coursearrange.common.core.base.result.R;
import com.lyk.coursearrange.common.exception.MZException;
import com.lyk.coursearrange.common.exception.logback.ExceptionUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@RestControllerAdvice
public class BaseExceptionHandler {

    @ExceptionHandler(value = {MZException.class})
    public R exceptionHandler(MZException e){
        log.error(ExceptionUtil.getMessage(e));
        return R.error().message(e.getMessage()).code(e.getCode());
    }

//    @ExceptionHandler
//    public com.baomidou.mybatisplus.extension.api.R<Object> methodArgumentNotValidException(MethodArgumentNotValidException e) {
//        Map<String, String> collect = e.getBindingResult().getFieldErrors().stream()
//                .collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
//        return com.baomidou.mybatisplus.extension.api.R.failed(collect.toString());
//    }

    @ExceptionHandler
    public com.baomidou.mybatisplus.extension.api.R<Object> methodArgumentNotValidException(MethodArgumentNotValidException e) {
        Map<String, String> collect = e.getBindingResult().getFieldErrors().stream()
                .collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
        return com.baomidou.mybatisplus.extension.api.R.failed(collect.toString());
    }

    @ExceptionHandler
    public com.baomidou.mybatisplus.extension.api.R<Object> runtimeException(RuntimeException e) {
        return com.baomidou.mybatisplus.extension.api.R.failed(e.getMessage());
    }
}
